package com.junbao.message.ui.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.junbao.message.infrastructure.prop.MessageConfig;
import com.junbao.message.infrastructure.result.Result;

/**
 * 通过ip验证权限
 * 
 * @author yilin
 *
 */
@WebFilter(filterName = "limitByIpFilter", urlPatterns = "/*")
public class LimitByIpFilter implements Filter {

	private static final MessageConfig CONFIG = new MessageConfig();
	private static final Logger LOGGER = LoggerFactory.getLogger(LimitByIpFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		String requestUri = request.getServletPath();
		// cbweb 地址为旧版本
		if (!requestUri.contains("/cbweb")) {
			String ip = request.getHeader("x-forwarded-for");
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
			if (ip.contains(",")) {
				ip = ip.split(",")[0];
			}
			String whiteIps = CONFIG.get("WHITE_LIST_IP");
			if (!whiteIpCheck(whiteIps, ip)) {
				LOGGER.info("非白名单ip访问: " + ip);
				writerLoginError(response);
				return;
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}

	private boolean whiteIpCheck(String whiteIps, String ip) {
		boolean whiteIpCheck = false;
		String[] ips = {};
		if (whiteIps.contains(",")) {
			ips = whiteIps.split(",");
		} else {
			ips = new String[] { whiteIps };
		}
		for (int i = 0; i < ips.length; i++) {
			if (ips[i].equals(ip)) {
				return true;
			}
		}
		return whiteIpCheck;
	}

	public void writerLoginError(HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		response.setHeader("content-type", "text/html;charset=UTF-8");
		Result result = new Result("9999", "该ip无访问权限");
		PrintWriter writer = response.getWriter();
		writer.print(JSONObject.toJSONString(result));
		return;
	}
}
